<script>
import { ArrowDown } from '@element-plus/icons-vue'
import UpdataNew from '@/components/UpdataNew'
import NewsDetails from '@/components/NewsDetails'
import AddNews from '@/components/AddNews'
import WaitNews from '@/components/WaitNews'
import { updateNews} from '@/api/news'
import { ElMessage } from 'element-plus'


export default {
  components: { UpdataNew, NewsDetails, ArrowDown, AddNews, WaitNews },

  data() {
    return {
      sum: 0,
      activeIndex: 0, // 默认选中"全部"
      isDialogVisible: false, // 弹窗显示状态
      currentForm: {}, // 待编辑的新闻数据
      newsList: [], //渲染新闻列表的数组
      allNewsList: [], // 存储所有新闻数据，用于搜索
      filteredNewsList: [], // 过滤后的新闻列表
      pendingNews: [], // 待发布新闻数组
      countList: [], //分类统计
      publishList:[],//获取的待发布新闻列表
      showDetail: false, //是否展示新闻详情组件
      showAdd: false, //是否展示添加新闻组件
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示数量
      currentNews: {}, // 当前选中的新闻数据
      searchKeyword: '', // 搜索关键词
      classList: [
        { value: 0, label: '全部', key: 'all' },
        { value: 1, label: '宏观形势', color: '#83DAAD', key: 'macroEnvironment' },
        { value: 2, label: '行业动态', color: '#EDBF45', key: 'industryTrends' },
        { value: 3, label: '产业链动态', color: '#8E63B7', key: 'industrialChainTrends' },
        { value: 4, label: '国际能源观察', color: '#E8954F', key: 'internationalEnergy' },
        { value: 5, label: '其他', color: '#697798', key: 'other' },
      ],
    }
  },
  mounted() {
    ;(this.fetchNewsList(), this.fetchPendingNews(), this.fetchCountClassReal())
  },

  methods: {
    // 根据分类值获取分类名称
    getClassLabel(value) {
      const classItem = this.classList.find((item) => item.value === value)
      return classItem ? classItem.label : value
    },
    // 根据分类值获取分类颜色
    getClassColor(value) {
      const classItem = this.classList.find((item) => item.value === value)
      return classItem ? classItem.color : '#909399'
    },
    // 获取新闻列表
    fetchNewsList() {
      // 获取当前页数据
      fetch(`/news/newsList?current=${this.currentPage}&currentSize=${this.pageSize}`)
        .then((res) => res.json())
        .then((res) => {
          console.log(res.data)
          this.newsList = res.data?.records || []
          this.filteredNewsList = this.newsList // 初始化过滤列表
          this.sum = res.data?.total

          // 获取所有数据用于搜索
          return fetch(`/news/newsList?current=1&currentSize=${this.sum || 1000}`)
        })
        .then((res) => res.json())
        .then((res) => {
          this.allNewsList = res.data?.records || []
        })
        .catch((error) => {
          console.error('获取新闻列表失败:', error)
        })
    },
    //获取待发布新闻数据
    fetchPendingNews() {
      fetch(`/news/newsList?current=1&currentSize=1000`)
        .then((res) => res.json())
        .then((res) => {
          // 根据API返回的实际数据结构进行映射
          const apiData = res.data || {}
          const listData = apiData.records || []

          // 只获取标记为待发布的新闻 (isSelect = 1)
          const pendingData = listData.filter((item) => item.isSelect === 1)

          // 将API数据映射为组件需要的格式
          this.pendingNews = pendingData.map((item) => ({
            id: item.id,
            newsTitle: item.newsTitle || item.title,
            classReal: item.classReal, 
            abstractReal: item.abstractReal,
            newsSource: item.newsSource,
            opPerson: item.opPerson,
            siteName: item.siteName,
            coverImage: item.coverImage,
            createTime: item.createTime,
            pubTime: item.pubTime,
            isPublished: item.isPublished,
          }))

          console.log('处理后的待发布新闻数据:', this.pendingNews)
        })
        .catch((error) => {
          console.error('获取待发布新闻失败:', error)
          this.pendingNews = []
        })
    },

    //统计各新闻类型的数量
    fetchCountClassReal() {
      fetch(`/news/selectAllCountClassReal`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({}),
      })
        .then((datas) => datas.json())
        .then((datas) => {
          for (let key in datas.data) {
            this.countList.push({
              key: key,
              count: datas.data[key],
            })
          }
        })
    },

    // 点击"编辑"按钮，打开弹窗并传入当前新闻数据
    handleEdit(news) {
      this.currentForm = {
        id: news.id,
        newsTitle: news.newsTitle || '',
        classReal: this.getClassLabel(news.classReal), 
        newsSource: news.siteName || '',
        sourceUrl: news.sourceUrl || '',
        abstractReal: news.abstractReal || '',
        markContent: news.markContent || '',
      }
      this.isDialogVisible = true
    },
    async handleConfirmEdit(form) {
      try {
        // 调用API更新数据
        await updateNews(form)
        // 更新成功后重新获取数据
        this.fetchNewsList()
        // 更新待发布新闻列表
        this.fetchPendingNews()

        console.log(`确认编辑新闻：${form.title}`)
        this.$message.success('新闻更新成功')
      } catch (error) {
        console.error('更新新闻失败:', error)
        this.$message.error('更新新闻失败，请重试')
      }
    },
    // 处理分页变化
    handlePageChange(newPage) {
      this.currentPage = newPage

      // 如果有allNewsList数据，直接从中切片获取当前页数据
      if (this.allNewsList && this.allNewsList.length > 0) {
        const startIdx = (this.currentPage - 1) * this.pageSize
        const endIdx = startIdx + this.pageSize
        this.newsList = this.allNewsList.slice(startIdx, endIdx)
        this.filteredNewsList = this.newsList
      } else {
        // 如果没有allNewsList数据，则重新获取
        this.fetchNewsList()
      }
    },
    // 处理点击新闻事件
    handleNewsClick(news) {
      this.currentNews = news
      this.showDetail = true
    },
    // 处理新闻类型选择
    handleSelect(value) {
      this.activeIndex = value
      this.currentPage = 1 // 重置页码为1
      this.fetchNewsListByCategory(value)
    },
    // 根据分类获取新闻列表
    fetchNewsListByCategory(category) {
      // 构建请求URL，获取全部数据
      const allUrl =
        category === -1
          ? `/news/newsList?current=1&currentSize=1000`
          : `/news/newsList?classReal=${category}&current=1&currentSize=1000`

      fetch(allUrl)
        .then((res) => res.json())
        .then((res) => {
          console.log(res.data)
          // 存储所有数据
          this.allNewsList = res.data?.records || []
          // 更新总数
          this.sum = res.data?.total || this.allNewsList.length

          // 只显示当前页的数据
          const startIdx = (this.currentPage - 1) * this.pageSize
          const endIdx = startIdx + this.pageSize
          this.newsList = this.allNewsList.slice(startIdx, endIdx)
          this.filteredNewsList = this.newsList // 更新过滤列表
        })
        .catch((error) => {
          console.error('获取新闻列表失败:', error)
          this.newsList = []
          this.filteredNewsList = []
          this.allNewsList = []
        })
    },
    // 搜索新闻
    searchNews() {
      if (!this.searchKeyword.trim()) {
        // 如果搜索关键词为空，显示所有新闻
        this.filteredNewsList = [...this.newsList]
        // 恢复原始总数
        this.fetchNewsList()
        return
      }

      // 过滤新闻，搜索标题和摘要
      const keyword = this.searchKeyword.toLowerCase()
      this.filteredNewsList = this.allNewsList.filter((news) => {
        const title = (news.newsTitle || '').toLowerCase()
        const abstract = (news.abstractReal || '').toLowerCase()
        return title.includes(keyword) || abstract.includes(keyword)
      })

      this.sum = this.filteredNewsList.length
    },
    // 监听搜索框输入变化
    handleSearchInput(event) {
      this.searchKeyword = event.target.value
      this.searchNews()
    },
    async addToPending(id) {
      if (this.pendingNews.length >= 10) {
        ElMessage.error('待发布新闻数量不能超过10条')
        return
      }
      const res = await updateNews({ id, isSelect: 1 })
      if (res.code === 200) {
        ElMessage.success('添加待发布新闻成功')
        this.newsList = this.newsList.map((it) => {
          if (it.id === id) {
            it.isSelect = 1
          }
          return it
        })
        // 同样更新filteredNewsList中的状态
        this.filteredNewsList = this.filteredNewsList.map((it) => {
          if (it.id === id) {
            it.isSelect = 1
          }
          return it
        })
        // 更新后重新获取待发布新闻列表
        this.fetchPendingNews()
      }
    },

    // 编辑待发布新闻
    editPendingNews(news) {
      // 从现有的新闻列表中查找完整的新闻数据
      const fullNewsData = this.allNewsList.find(item => item.id === news.id);
      
      if (fullNewsData) {
        // 设置编辑表单数据
        this.currentForm = {
          id: fullNewsData.id,
          newsTitle: fullNewsData.newsTitle || '',
          classReal: this.getClassLabel(fullNewsData.classReal), // 使用getClassLabel方法获取正确的标签名称
          abstractReal: fullNewsData.abstractReal || '',
          newsSource: fullNewsData.newsSource || '',
          sourceUrl: fullNewsData.sourceUrl || '',
          summary: fullNewsData.abstractReal || '',
          markContent: fullNewsData.markContent || '',
        }
        // 打开编辑弹窗
        this.isDialogVisible = true
      } else {
        // 如果在 allNewsList 中找不到，尝试从API获取
        fetch(`/news/newsList?current=1&currentSize=1000`)
          .then(res => res.json())
          .then(res => {
            if (res.code === 200 && res.data && res.data.records) {
              const newsData = res.data.records.find(item => item.id === news.id);
              if (newsData) {
                // 设置编辑表单数据
                this.currentForm = {
                  id: newsData.id,
                  newsTitle: newsData.newsTitle || '',
                  classReal: this.getClassLabel(newsData.classReal), // 使用getClassLabel方法获取正确的标签名称
                  newsSource: newsData.siteName || '',
                  sourceUrl: newsData.sourceUrl || '',
                  abstractReal: newsData.abstractReal || '',
                  markContent: newsData.markContent || '',
                }
                // 打开编辑弹窗
                this.isDialogVisible = true
              } else {
                this.$message.error('找不到该新闻详情')
              }
            } else {
              this.$message.error('获取新闻详情失败')
            }
          })
          .catch(error => {
            console.error('获取新闻详情失败:', error)
            this.$message.error('获取新闻详情失败，请重试')
          })
      }
    },


    // 从待发布列表中移除新闻
    removeFromPending(id) {
      this.pendingNews = this.pendingNews.filter((news) => news.id !== id)
      // 更新新闻列表中的状态
      this.newsList = this.newsList.map((item) => {
        if (item.id === id) {
          return { ...item, isSelect: 0 }
        }
        return item
      })
      // 同样更新filteredNewsList中的状态
      this.filteredNewsList = this.filteredNewsList.map((item) => {
        if (item.id === id) {
          return { ...item, isSelect: 0 }
        }
        return item
      })
      // 重新获取待发布新闻列表以确保数据同步
      this.fetchPendingNews()
    },
    // 切换新闻的发布状态
    async togglePublishStatus(news, event) {
      // 阻止事件冒泡
      if (event) {
        event.stopPropagation();
        event.preventDefault();
      }

      if (news.isSelect === 1) {
        // 从待发布状态移除
        const res = await updateNews({ id: news.id, isSelect: 0 })
        if (res.code === 200) {
          ElMessage.success('已从待发布新闻移除')
          // 更新新闻列表中的状态
          this.newsList = this.newsList.map((item) => {
            if (item.id === news.id) {
              return { ...item, isSelect: 0 }
            }
            return item
          })
          // 同样更新filteredNewsList中的状态
          this.filteredNewsList = this.filteredNewsList.map((item) => {
            if (item.id === news.id) {
              return { ...item, isSelect: 0 }
            }
            return item
          })
          // 重新获取待发布新闻列表
          this.fetchPendingNews()
        }
      } else {
        // 加入待发布
        this.addToPending(news.id)
      }
    },
  },
}
</script>

<template>
  <div class="newsBox">
    <div class="content-title">
      <div class="text">新闻内容：</div>
      <img src="../../assets/搜索.svg" class="search" />
      <input
        type="text"
        placeholder="请输入文章摘要或标题"
        @input="handleSearchInput"
        v-model="searchKeyword"
      />
    </div>
    <div class="content-title">
      <div class="text">新闻类型：</div>

      <div
        class="type"
        v-for="(item, index) in classList"
        :key="item.value"
        :class="{ light: item.value === activeIndex }"
        @click="handleSelect(item.value)"
      >
        {{ item.label }} ({{ item.key === 'all' ? sum : countList[index - 1]?.count }})
      </div>
    </div>
    <div class="content-title">
      <div class="text">筛选条件：</div>
      <el-dropdown trigger="click" style="margin-right: 20px">
        <span class="el-dropdown-link">
          时间降序
          <el-icon class="el-icon--right">
            <arrow-down />
          </el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>全部</el-dropdown-item>
            <el-dropdown-item>时间升序</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <el-dropdown trigger="click" style="margin-right: 20px">
        <span class="el-dropdown-link">
          时间范围
          <el-icon class="el-icon--right">
            <arrow-down />
          </el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>全部</el-dropdown-item>
            <el-dropdown-item>最近半年</el-dropdown-item>
            <el-dropdown-item>最近一年</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <el-dropdown trigger="click" style="margin-right: 20px">
        <span class="el-dropdown-link">
          添加方式
          <el-icon class="el-icon--right">
            <arrow-down />
          </el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>全部</el-dropdown-item>
            <el-dropdown-item>手动添加</el-dropdown-item>
            <el-dropdown-item>自动添加</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <el-dropdown trigger="click" style="margin-right: 20px">
        <span class="el-dropdown-link">
          发布状态
          <el-icon class="el-icon--right">
            <arrow-down />
          </el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>全部</el-dropdown-item>
            <el-dropdown-item>已发布</el-dropdown-item>
            <el-dropdown-item>未发布</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <div class="addNews" v-permission="'write'">
      <span @click="showAdd = true" style="line-height: 40px">+ 手动添加新闻</span>
      <AddNews v-model="showAdd" @refresh="fetchNewsList" />
    </div>

    <div class="main-content">
      <div class="news-list-container">
        <div class="news-content-wrapper">
          <div class="news-content" v-for="(news, index) in filteredNewsList" :key="news.id" @click.stop="handleNewsClick(news)">
            <div class="flex items-center">
              <span
                class="title-color"
                :style="{
                  backgroundColor: getClassColor(news.classReal),
                  color: '#fff',
                  padding: '2px 6px',
                  borderRadius: '4px',
                }"
                >{{ getClassLabel(news.classReal) }}</span
              >
              <h4 class="newTitle" >
                {{ news.newsTitle }}
              </h4>
            </div>
            <div class="content-middle">{{ news.abstractReal }}</div>
            <div class="content-footer flex justify-between">
              <div class="flex items-center">
                <img :src="news.coverImage" />
                <span style="margin-right: 15px"
                  >{{ news.siteName
                  }}{{ news.opPerson ? '· 由' + news.opPerson + '更新' : '' }}</span
                >
                <span style="color: #a8a8a8">{{ news.createTime }}</span>
              </div>
              <div class="flex items-center">
                <span style="margin-right: 5px; color: #a8a8a8">{{ news.pubTime }}</span>
                <img
                  src="../../assets/btn-remove.svg"
                  v-if="news.isSelect === 1"
                  style="margin-left: 5px; width: 25px"
                  v-permission="'write'"
                />
                <button
                  style="margin-right: 15px; cursor: pointer"
                  @click.stop="togglePublishStatus(news, $event)"
                  :class="{ addpublish: news.isSelect !== 1 }"
                 v-permission="'write'"
                >
                  {{ news.isSelect === 1 ? '移除' : '+ 加入待发布' }}
                </button>
                <img src="../../assets/编辑.svg" v-permission="'write'" />
                <button v-permission="'write'"  @click.stop="handleEdit(news)" style="color: #068ad6; cursor: pointer">
                  编辑
                </button>
              </div>
            </div>
          </div>
        </div>
        <div class="footer">
          <span>共{{ sum }}条</span>
          <el-pagination
            background
            layout="prev, pager, next"
            :total="sum"
            :current-page="currentPage"
            :page-size="pageSize"
            @current-change="handlePageChange"
          />
        </div>
      </div>
      <div class="rightbox">
        <div class="right-header">待发布新闻 ({{ this.pendingNews.length }})</div>
        <div>
          <WaitNews
            :pendingNews="pendingNews"
            @remove-news="removeFromPending"
            @edit-news="editPendingNews"
          />
        </div>
        <button class="releasebtn" v-permission="'write'" @click="$router.push('/published')">发布设置</button>
      </div>
    </div>

    <updata-new
      v-model:visible="isDialogVisible"
      :initial-form="currentForm"
      @confirm-edit="handleConfirmEdit"
    />
  </div>

  <NewsDetails v-model="showDetail" :newsData="currentNews" @click.stop />
</template>

<style scoped>
.newsBox {
  padding: 30px 25px;
}

.main-content {
  display: flex;
  gap: 20px;
}

.news-list-container {
  flex: 1;
  height: 600px;
  margin-top: 10px;
  display: flex;
  flex-direction: column;
}

.rightbox {
  padding: 10px 0 0 10px;
  width: 400px;
  border-left: 1px solid #eee;
  height: 600px;
  display: flex;
  flex-direction: column;
}

.content-title {
  position: relative;
  display: flex;
  margin-bottom: 30px;
}

.content-title .text {
  margin-right: 20px;
  white-space: nowrap;
}

.content-title .type {
  margin-right: 20px;
  white-space: nowrap;
  cursor: pointer;
}

.light {
  color: #068ad6;
}

.addNews {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 40px;
  border: 1px dashed #ccc;
  cursor: pointer;
}

.newTitle {
  font-weight: bold;
  cursor: pointer;
}

.newTitle:hover {
  color: #068ad6;
}

.content-title input {
  width: 260px;
  height: 30px;
  padding: 0 30px;
  border: 1px solid #e5e5e5;
}

.content-title input:focus {
  outline: none;
}

.content-title input::placeholder {
  color: #d9d9d9;
}

.search {
  position: absolute;
  left: 106px;
  top: 6px;
  width: 20px;
  height: 20px;
}

.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
  font-size: 16px;
}

.news-content-wrapper{
  flex: 1;
  overflow-y: auto;
  scrollbar-width: none;
}

.news-content {
  height: 130px;
  margin-top: 10px;
  border-bottom: 1px solid #eee;
}

.title-color {
  background-color: #e8954f;
  color: #fff;
  border-radius: 5px;
  padding: 3px 8px;
  margin-right: 10px;
}

.content-middle {
  padding: 15px 0;
  color: #a8a8a8;
}

.addpublish {
  color: #068ad6;
  margin-right: 5px;
  cursor: pointer;
}

.content-footer img {
  width: 30px;
  height: 30px;
  margin-right: 10px;
  border-radius: 50%;
}

.footer {
  display: flex;
  height: 60px;
  line-height: 60px;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  border-top: 1px solid #e6e6e6;
  flex-shrink: 0;
}

.right-header {
  margin: 0 0 20px 10px;
  font-weight: bold;
  font-size: 18px;
  flex-shrink: 0;
}

.releasebtn {
  width: 100%;
  border-radius: 10px;
  height: 40px;
  background-color: #068ad6;
  color: #fff;
  cursor: pointer;
  margin-top: 10px;
  flex-shrink: 0;
}

.rightbox > div:nth-child(2) {
  flex: 1;
  overflow-y: auto;
  scrollbar-width: none;
}
</style>
